// src/routes/securities/+page.ts
import type { PageLoad } from './$types';
import * as commands from '$lib/commands'

import { sampleStocks } from './sampleData';
import type { IpcResponse, ListParams, Security, SecurityFilter } from '$lib/bindings';

export const load: PageLoad = async ({ fetch, params, url }) => {
    const currentPage = parseInt(url.searchParams.get('page') || '1', 10) - 1; // Get the page parameter from the URL query
    const pageSize = 100
    console.log(`(securities/+page.ts) load currentPage = ${currentPage} `)

    try {

        // Define the argument
        const args: ListParams<SecurityFilter> = {
            page: currentPage,
            size: pageSize,
            filter: null,
        }

        const res: IpcResponse<Security[]> = await commands.list_securities(args)

        if (res.error) {
            // If the response status is not OK, throw an error
            throw new Error(`(securities/+page.ts)Server returned an error: ${res.error}`);
        }

        console.log("(securities/+page.ts) res=", res);

        // If the server response is empty, return sample data
        if (res.result) {
            return {
                currentPage: currentPage,
                pageSize: pageSize,
                securities: res.result.data
            };
        }

        return {
            currentPage: currentPage,
            pageSize: pageSize,

            securities: []
        };
    } catch (error) {
        // If there's any error (e.g., network issue), return sample data
        console.error('(securities/+page.ts) Error fetching securities:', error);
        return {
            currentPage: currentPage,
            pageSize: pageSize,

            securities: []
        };
    }
};